<?php

namespace App\Http\Controllers\Api;

use App\CustomerClue;
use App\CustomerServiceImgs;
use App\CustomerServiceRecord;
use App\CustomerXStaff;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Staff;
use App\User;
use App\UserInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CrmController extends Controller
{
    public function getPublicCustomerClueList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $staff_id   = Staff::getUserStaffId($user->id);
        if (!$staff_id)
            return response()->json(['level' => 'error','message' => '员工才可以操作','data' => '']);
        $page       = $request->input('page',1);
        $limit      = $request->input('limit',10);

        $data = CustomerClue::whereIsSelect(0);
        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page = $page-1;
        $page_info['total'] = $data->count();
        $data = $data->orderByDesc('id')->limit($limit)->offset($page * $limit)->get();
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$data,'page_info'=>$page_info]);

    }

    public function getMyCustomerList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $page       = $request->input('page',1);
        $limit      = $request->input('limit',10);
        $staff_id   = Staff::getUserStaffId($user->id);
        if (!$staff_id)
            return response()->json(['level' => 'error','message' => '员工才可以操作','data' => '']);
        $data = CustomerXStaff::whereStaffId($staff_id);
        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page = $page-1;
        $page_info['total'] = $data->count();
        $data = $data->orderByDesc('id')->limit($limit)->offset($page * $limit)->get();
        if (count($data) > 0){
            foreach ($data as $item){
                $item->customer_detail = CustomerClue::whereId($item->customer_clues_id)->first();
            }
        }
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$data,'page_info'=>$page_info]);
    }

    public function getCustomerServiceList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $page       = $request->input('page',1);
        $limit      = $request->input('limit',10);
        $customer_clue_id  = $request->input('customer_clues_id',0);
        if (!$customer_clue_id)
            return response()->json(['level' => 'error','message' => '未选择客户','data' => '']);
        $staff_id   = Staff::getUserStaffId($user->id);
        if (!$staff_id)
            return response()->json(['level' => 'error','message' => '员工才可以操作','data' => '']);
        $data = CustomerServiceRecord::whereCustomerCluesId($customer_clue_id);
        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page = $page-1;
        $page_info['total'] = $data->count();
        $data = $data->orderByDesc('id')->limit($limit)->offset($page * $limit)->get();
        if (count($data) > 0){
            foreach ($data as $item){
                $item->customer_detail  = CustomerClue::whereId($item->customer_clues_id)->first();
                $item->img_urls         = CustomerServiceImgs::getServicesImgUrlArray($item->id);
                $item->video_url        = FileManager::getVideoUrl($item->video_id);
                $item->staff_name       = UserInfo::getStaffName($item->staff_id);
                $item->stuff_photo_url  = UserInfo::getStaffPhotoUrl($item->staff_id);
            }
        }
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$data,'page_info'=>$page_info]);
    }

    public function addServiceRecord(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $job_content        = $request->input('job_content','');
        $customer_clue_id   = $request->input('customer_clue_id',0);
        $img_ids            = $request->input('img_ids',[]);
        $video_id           = $request->input('video_id',0);
        if (!$customer_clue_id)
            return response()->json(['level' => 'error','message' => '未选择客户','data' => '']);
        $staff_id   = Staff::getUserStaffId($user->id);
        if (!$staff_id)
            return response()->json(['level' => 'error','message' => '员工才可以操作','data' => '']);
        $exist = CustomerServiceRecord::whereStaffId($staff_id)
            ->whereCustomerCluesId($customer_clue_id)
            ->orderByDesc('id')
            ->first();
        if ($exist){
            if (strtotime($exist->created_at) + 60 > time()){
                return response()->json(['level' => 'error','message' => '60秒内不能重复提交','data' => '']);
            }
        }
        $record = new CustomerServiceRecord();
        $record->customer_clues_id  = $customer_clue_id;
        $record->staff_id           = $staff_id;
        $record->job_content    = $job_content;
        $record->video_id       = $video_id;
        $record->save();
        if (count($img_ids) > 0){
            foreach ($img_ids as $img_id){
                $temp = new CustomerServiceImgs();
                $temp->customer_service_record_id   = $record->id;
                $temp->img_id                       = $img_id;
                $temp->save();
            }
        }
        return response()->json(['level' => 'success','message' => '提交成功']);
    }

    public function pluckCustomer(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $staff_id   = Staff::getUserStaffId($user->id);
        if (!$staff_id)
            return response()->json(['level' => 'error','message' => '员工才可以操作','data' => '']);
        $customer_clue_id   = $request->input('customer_clue_id',0);
        if (!$customer_clue_id)
            return response()->json(['level' => 'error','message' => '未选择客户','data' => '']);
        try {
            \DB::beginTransaction();
            /** @var  CustomerClue $customer */
            $customer = CustomerClue::whereId($customer_clue_id)->lockForUpdate()->first();
            if (!$customer){
                \DB::rollBack();
                return response()->json(['level' => 'error','message' => '客户不存在','data' => '']);
            }

            if ($customer->is_select){
                \DB::rollBack();
                return response()->json(['level' => 'error','message' => '客户已被他人选走','data' => '']);
            }

            $customer->is_select = 1;
            $customer->save();
            $staffXCustomer = CustomerXStaff::whereCustomerCluesId($customer->id)->lockForUpdate()->first();
            if (!$staffXCustomer){
                $staffXCustomer = new CustomerXStaff();
                $staffXCustomer->customer_clues_id = $customer->id;
            }
            $staffXCustomer->staff_id = $staff_id;
            $staffXCustomer->save();
            \DB::commit();

        } catch (\Exception $e){
            \DB::rollBack();
            \Log::notice('pluckCustomer:'.$e->getMessage());
            return response()->json(['level' => 'error','message' => '操作失败：'.$e->getMessage(),'data' => '']);
        }
        return response()->json(['level' => 'success','message' => '操作成功','data' =>$customer]);

    }
}
